package com.example.coroutines

import android.os.Handler
import android.os.Looper
import android.util.Log
import org.junit.Test
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 测试Retrofit
 *
 * @author zhouronghua
 * @time 2021/12/24 10:28 下午
 */
class TestRetrofit {

    val TAG = "TestRetrofit"

    var handler:Handler? = null

    val gitHubServiceApi by lazy {
        val retrofit = retrofit2.Retrofit.Builder()
            .baseUrl("https://api.github.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        retrofit.create(GitHubServiceApi::class.java)
    }

    @Test
    fun testRetrofit() {
        handler = Handler(Looper.getMainLooper())
        gitHubServiceApi.getUser("bennyhuo").enqueue(object : Callback<User> {
            override fun onFailure(call: Call<User>, t: Throwable) {
                handler?.post { showError(t) }
            }

            override fun onResponse(call: Call<User>, response: Response<User>) {
                handler?.post { response.body()?.let(::showUser) ?: showError(NullPointerException()) }
            }
        })
    }

    private fun showUser(user: User) {
        Log.d(TAG, "" + user.name)
    }

    private fun showError(t: Throwable) {
        Log.d(TAG, "" + t.message)
    }

}